/**
 * 考勤管理-假期统计
 */
import React, { useEffect, useState } from 'react';
import { connect } from 'umi';
import { history } from 'umi';
import { eventTrack } from '@/utils/track';
import { getemployeelist } from '@/services/attendance/overtime';

import {
    Form,
    Button,
    Table,
    Card,
    Modal,
    Popover,
    Input,
    Row,
    Col,
    Select,
    InputNumber,
    Radio,
    message,
    ConfigProvider
} from 'antd';
import { utils } from 'vv-frontend-components';
import moment from 'moment';
import clone from 'lodash/clone';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import AuthCode from '@/utils/auth/AuthCode';
import authHelpr from '@/utils/auth/helper';
import { dateConversion, download } from '@/utils/utils';
import { SearchInput } from '@/components/UserForm';
import { Pagination } from '@/components';
import OrganizationSelect from '@/components/OrganizationSelect';
import Vacation from './Components/Vacation';
import SearchForm from './Components/SearchForm';
import styles from './VacationBalance.less';

const { deepTrim } = utils;

const { TextArea } = Input;

const { checkCode } = authHelpr;
const formLayout = {
    labelCol: {
        md: { span: 8 }
    },
    wrapperCol: {
        md: { span: 14 }
    }
};
const { Option } = Select;

const VacationBalance = ({ form, dispatch, loading, vacationBalance, user, ...rags }) => {
    const { getFieldDecorator } = form;
    const User = user.currentUser; // 登陆人信息
    const { authCode } = new AuthCode(rags.route.code);
    const {
        pagination,
        vacationBalanceList,
        vacation,
        timeUnitTypeList,
        allSelectVacation,
        vocationRecordTypeList,
        // companyList,
        modalVacation,
        popoverList
    } = vacationBalance;
    const [companyId, setCompanyId] = useState(null);
    const [modalCompanyId, setModalCompanyId] = useState(null);
    const [modalUserInfo, setModalUserInfo] = useState(null);
    // const [companyPath, setCompanyPath] = useState(User?.firstOrgInfo?.firstCompanyPath);  [DELETE] 公司获取参数的接口变更, 参数变更
    const { firstOrgInfo = {} } = User;
    const { firstCompanyCode } = firstOrgInfo;

    const [visible, setVisible] = useState(false);
    const [tableColumns, setTableColumns] = useState([]);
    const [curSelectVacation, setCurSelectVacation] = useState([]); // 选中code
    const [curSelectVacationList, setCurSelectVacationList] = useState([]); // 选中item

    // const isAdditionalType = ['CommonSick', 'CommonPerson', 'CommonPaid']; // 用于modal修改余额天数的天/时需要判断的字段
    const columns = [
        {
            title: '工号',
            dataIndex: 'userNo',
            width: 140,
            fixed: 'left',
            className: styles.row
        },
        {
            title: '姓名',
            dataIndex: 'employeeName',
            width: 140,
            fixed: 'left',
            className: styles.row
        },
        {
            title: '组织机构',
            dataIndex: 'departmentName',
            width: 140,
            fixed: 'left',
            className: styles.row
        }
    ];

    const getPopoverList = (record, leaveCode, v) => {
        if (v) {
            dispatch({
                type: 'vacationBalance/getPopoverList',
                payload: {
                    companyCode: record.companyCode,
                    // departmentId: record.departmentId,
                    employeeCode: record.employeeCode,
                    leaveCode
                }
            });
        } else {
            dispatch({
                type: 'vacationBalance/save',
                payload: {
                    popoverList: []
                }
            });
        }
    };
    const getPopoverContent = () =>
        popoverList.map(item => (
            <div key={item.leaveCode}>
                {moment(item.startTime).format('YYYYMMDD')}-{moment(item.endTime).format('YYYYMMDD')}：
                {dateConversion(item.value, 8)}
            </div>
        ));
    const getColumns = (addColumns = []) => {
        const copyColumns = clone(columns);
        addColumns.map(item => {
            copyColumns.push({
                title: (
                    <div className={styles.titleOverflow} title={item.leaveName}>
                        {item.leaveName}
                    </div>
                ),
                render: (text, record) => {
                    if (item.openState === '0') {
                        return '不限';
                    }
                    const dom = [];
                    for (let index = 0; index < record.vocationList.length; index += 1) {
                        const list = record.vocationList[index];
                        if (list.leaveCode === item.leaveCode) {
                            dom.push(
                                <div key={index}>
                                    <Popover
                                        content={getPopoverContent()}
                                        title={`${item.leaveName}-可用余额`}
                                        onVisibleChange={v => {
                                            getPopoverList(record, item.leaveCode, v);
                                        }}
                                        trigger="click"
                                    >
                                        <a className={styles.getPopover}>{dateConversion(list.value, 8)}</a>
                                    </Popover>
                                </div>
                            );
                        }
                    }
                    return dom.length > 0 ? dom : '0';
                },
                width: addColumns.length > 6 ? 140 : '',
                className: addColumns.length > 6 ? styles.row : ''
            });
            return '';
        });
        setTableColumns(copyColumns);
    };
    const setOpiton = dict =>
        dict &&
        dict.map(item => (
            <Option value={item.dictValue} key={item.dictValue}>
                {item.dictName}
            </Option>
        ));

    const setOpiton2 = dict =>
        dict &&
        dict.map(item => {
            if (item.leaveCode === 'CommonPaid') {
                return '';
            }
            return (
                <Option value={item.leaveCode} key={item.leaveCode}>
                    {item.leaveName}
                </Option>
            );
        });
    const getPayload = type => {
        const values = form.getFieldsValue();
        const payload = {
            companyCode: values.companyDepart?.companyId,
            departmentCode: values.companyDepart?.departmentId,
            // companyId: 101,
            // departmentId: 112,
            employeeCodes: values.employeeIds || [],
            pageNo: type ? 1 : pagination.current,
            pageSize: type ? 10 : pagination.pageSize
        };
        return payload;
    };
    const fetchVacationList = type => {
        // 发起请求
        dispatch({
            type: 'vacationBalance/fetchVacationList',
            payload: getPayload(type)
        });
    };
    // 获取显示列内容
    const getColumnlist = () => {
        dispatch({
            type: 'vacationBalance/getColumnlist',
            payload: {
                companyId: companyId || firstCompanyCode
            }
        });
    };

    const onSearch = type => {
        fetchVacationList(type);
        // 埋点
        eventTrack({
            eventName: 'personnel_management_attendance_vacationBalance_serch_click',
            eventProps: {
                key_works: JSON.stringify(form.getFieldsValue() || {})
            }
        });
    };
    // 发生变化
    const onChange = id => {
        setCompanyId(id);
    };
    // 获取修改假期余额里的字典
    const getModalDict = () => {
        dispatch({
            type: 'vacationBalance/getModalDict'
        });
    };
    // 获取公司树数据
    const getModalCompany = () => {
        console.log(User);
        dispatch({
            type: 'vacationBalance/getModalCompany'
        });
    };
    // 修改假期余额Modal取消
    const handleCancel = e => {
        const { eType } = e;
        setVisible(false);
        setModalCompanyId(null);
        form.resetFields([
            'companyId',
            'employeeId',
            'leaveCode',
            'leaveBalance',
            'vocationRecordType',
            'remark',
            'timeUnitType',
            'radioTime'
        ]);
        // 埋点
        if (eType !== 'search') {
            eventTrack({
                eventName: 'personnel_management_attendance_vacationBalance_edit_cancel_click',
                eventProps: {
                    label: '假期统计-修改假期余额-取消'
                }
            });
        }
    };
    // 获取开始时间
    const fetchStartTime = allValues => {
        if (allValues.vocationRecordType === 'add') {
            if (allValues.radioTime) {
                return moment(moment().startOf('year')).format('YYYY-MM-DD 00:00:00');
            }
            return moment(
                moment()
                    .startOf('year')
                    .add(1, 'y')
            ).format('YYYY-MM-DD 00:00:00');
        }
        return '';
    };
    // 获取结束时间
    const fetchEndTime = allValues => {
        if (allValues.vocationRecordType === 'add') {
            if (allValues.radioTime) {
                return moment(moment().endOf('year')).format('YYYY-MM-DD 23:59:59');
            }
            return moment(
                moment()
                    .endOf('year')
                    .add(1, 'y')
            ).format('YYYY-MM-DD 23:59:59');
        }
        return '';
    };
    // 修改假期余额Modal提交
    const handleOk = () => {
        const allValues = form.getFieldsValue();

        form.validateFields(['companyId', 'employeeId', 'leaveCode', 'leaveBalance', 'timeUnitType', 'remark'], err => {
            if (!err) {
                dispatch({
                    type: 'vacationBalance/updatevocationbalance',
                    payload: {
                        companyCode: modalCompanyId || User.companyId,
                        departmentCode: modalUserInfo.departmentCode || '',
                        employeeCode: modalUserInfo.employeeCode || '',
                        employeeName: modalUserInfo.employeeName || '',
                        endTime: fetchEndTime(allValues),
                        leaveBalance: allValues.leaveBalance || 0,
                        leaveCode: allValues.leaveCode || '',
                        remark: allValues.remark,
                        startTime: fetchStartTime(allValues),
                        timeUnitType: allValues.timeUnitType || '',
                        userNo: modalUserInfo.userNo || '',
                        vocationRecordType: allValues.vocationRecordType
                    }
                }).then(res => {
                    if (res) {
                        if (res.code === 10000) {
                            // 埋点
                            eventTrack({
                                eventName: 'personnel_management_attendance_vacationBalance_edit_sumbit_click',
                                eventProps: {
                                    status: 0
                                }
                            });
                            message.success(res.msg);
                            fetchVacationList();
                            handleCancel({
                                eType: 'search'
                            });
                        } else {
                            message.error(res.msg);
                        }
                    }
                });
            } else {
                // 埋点
                eventTrack({
                    eventName: 'personnel_management_attendance_vacationBalance_edit_sumbit_click',
                    eventProps: {
                        status: 1,
                        error_info: JSON.stringify(err)
                    }
                });
            }
        });
    };

    // 当modal公司树发生变化后
    const handleCompanyChange = value => {
        setModalCompanyId(value);
        form.resetFields(['employeeId', 'leaveCode']);
    };
    // 获取modal假期类型内容
    const getModalColumnlist = () => {
        dispatch({
            type: 'vacationBalance/getModalColumnlist',
            payload: {
                companyCode: modalCompanyId || User.companyId
            }
        });
    };
    // 获取modal选择的用户信息
    const getModalUserInfo = (v, option) => {
        if (v) {
            setModalUserInfo(option.props.info);
        }
    };

    // 导出假期余额
    const exportVacation = async () => {
        const values = form.getFieldsValue();
        download({
            getData: () =>
                dispatch({
                    type: 'vacationBalance/fetchExportlist',
                    payload: deepTrim({
                        companyCode: values.companyDepart?.companyId,
                        departmentCode: values.companyDepart?.departmentId,
                        employeeCodes: values.employeeIds || [],
                        columnList: curSelectVacation,
                        pageNo: pagination.current,
                        pageSize: pagination.pageSize
                    })
                })
        });
    };
    // 表格页码发生改变
    const changeTable = async newPagination => {
        await dispatch({
            type: 'vacationBalance/save',
            payload: {
                pagination: {
                    ...vacationBalance.pagination,
                    ...newPagination
                }
            }
        });
    };
    // 当显示列发生改变的时候
    const changeExportVacation = v => {
        const arr = [];
        v.map(item => {
            arr.push(item.leaveCode);
            return '';
        });
        setCurSelectVacationList(v);
        setCurSelectVacation(arr);
    };

    // 组件卸载时候 清空表单请求参数（高级搜索内容、分页、排序字段）
    useEffect(
        () => () => {
            dispatch({
                type: 'vacationBalance/save',
                payload: {
                    orderBy: '',
                    pagination: {
                        ...pagination,
                        pageSize: 10,
                        current: 1
                    }
                }
            });
        },
        []
    );
    // 由于后端技术实现上有问题，这里由前端做分页处理
    // (n-1)*m,n*m
    const renderList = () => {
        const { pageSize, current } = pagination;
        return vacationBalanceList.slice((current - 1) * pageSize, current * pageSize);
    };

    useEffect(() => {
        fetchVacationList();
    }, [pagination.pageSize, pagination.current, User]);
    useEffect(() => {
        getColumnlist();
    }, [companyId, User]);
    useEffect(() => {
        getColumns(vacation);
        setCurSelectVacation(allSelectVacation);
    }, [vacation, allSelectVacation]);
    useEffect(() => {
        getColumns(curSelectVacationList.length > 0 ? curSelectVacationList : vacation);
    }, [popoverList]);
    useEffect(() => {
        getModalDict();
        getModalCompany();
    }, []);
    useEffect(() => {
        getPopoverContent();
    }, [popoverList, loading]);
    useEffect(() => {
        getModalColumnlist();
    }, [modalCompanyId, User]);
    return (
        <PageHeaderWrapper>
            <Card
                bordered={false}
                title="员工假期余额"
                extra={
                    checkCode(authCode('edit')) ? (
                        <Button
                            type="primary"
                            onClick={() => {
                                setVisible(true);
                                // 埋点
                                eventTrack({
                                    eventName: 'personnel_management_attendance_vacationBalance_edit_click',
                                    eventProps: {
                                        label: '假期统计-修改假期余额'
                                    }
                                });
                            }}
                        >
                            修改假期余额
                        </Button>
                    ) : (
                        ''
                    )
                }
            >
                <div className={styles.flex}>
                    <SearchForm
                        form={form}
                        user={User}
                        onSearch={() => {
                            onSearch('reset');
                        }}
                        onChange={id => {
                            onChange(id);
                        }}
                        style={{ display: 'inline-block' }}
                        code={rags.route.code}
                    />
                    <div className={styles.flexRight}>
                        {checkCode(authCode('import')) ? (
                            <Button
                                onClick={async () => {
                                    // 埋点
                                    await eventTrack({
                                        eventName: 'personnel_management_attendance_vacationBalance_import_click',
                                        eventProps: {
                                            label: '假期统计-批量发放余额'
                                        }
                                    });
                                    history.push({
                                        pathname: '/office/personnelManagement/attendance/vacationBalance/import',
                                        query: {
                                            id: companyId || User.companyId
                                        }
                                    });
                                }}
                            >
                                批量发放余额
                            </Button>
                        ) : (
                            ''
                        )}
                        {checkCode(authCode('export')) ? (
                            <Button
                                onClick={() => {
                                    exportVacation();
                                    // 埋点
                                    eventTrack({
                                        eventName: 'personnel_management_attendance_vacationBalance_export_click',
                                        eventProps: {
                                            label: '假期统计-导出'
                                        }
                                    });
                                }}
                                loading={loading.effects['vacationBalance/fetchExportlist']}
                            >
                                导出
                            </Button>
                        ) : (
                            ''
                        )}
                    </div>
                </div>
                <Vacation
                    form={form}
                    vacation={vacation}
                    returnOnChange={v => {
                        getColumns(v);
                        changeExportVacation(v);
                    }}
                    companyId={companyId}
                />
                <Table
                    loading={loading.effects['vacationBalance/fetchVacationList']}
                    dataSource={renderList()}
                    columns={tableColumns}
                    scroll={{ x: 'max-content', scrollToFirstRowOnChange: true }}
                    rowKey="id"
                    onChange={changeTable}
                    pagination={false}
                />
                <Pagination
                    onChange={changeTable}
                    {...pagination}
                    loading={loading.effects['vacationBalance/fetchVacationList']}
                />
            </Card>
            <Modal
                width={600}
                visible={visible}
                title="修改假期余额"
                onOk={handleOk}
                onCancel={handleCancel}
                footer={[
                    <Button key="back" onClick={handleCancel}>
                        取消
                    </Button>,
                    <Button key="submit" type="primary" loading={false} onClick={handleOk}>
                        确定
                    </Button>
                ]}
            >
                <ConfigProvider getPopupContainer={trigger => trigger.parentNode}>
                    <Form layout="horizontal" {...formLayout}>
                        <Form.Item label="适用公司：" labelCol={{ md: 8 }} wrapperCol={{ md: 9 }}>
                            {getFieldDecorator('companyId', {
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择适用公司'
                                    }
                                ],
                                initialValue: firstCompanyCode
                            })(
                                <OrganizationSelect
                                    isStrictly
                                    style={{ width: 250 }}
                                    isNeedPermission
                                    onChange={handleCompanyChange}
                                />
                            )}
                        </Form.Item>
                        <Form.Item label="人员：" labelCol={{ md: 8 }} wrapperCol={{ md: 9 }}>
                            {getFieldDecorator('employeeId', {
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入员工姓名'
                                    }
                                ]
                            })(
                                <SearchInput
                                    params={{
                                        organizationCode: modalCompanyId || firstCompanyCode,
                                        queryCurrentCompanyEmployee: 'true'
                                    }}
                                    getData={params =>
                                        getemployeelist(params).then(res => {
                                            if (res && res.code === 10000) {
                                                return res.data || [];
                                            }
                                            return [];
                                        })
                                    }
                                    selectProps={{
                                        placeholder: '请输入员工姓名',
                                        allowClear: true,
                                        style: { width: '100%' }
                                    }}
                                    fieldsName={{
                                        value: 'employeeCode',
                                        title: 'employeeName',
                                        extraParams: 'userName',
                                        vacation: true
                                    }}
                                    onChange={(v, option) => {
                                        getModalUserInfo(v, option);
                                    }}
                                />
                            )}
                        </Form.Item>
                        <Form.Item label="假期类型：" labelCol={{ md: 8 }} wrapperCol={{ md: 9 }}>
                            {getFieldDecorator('leaveCode', {
                                rules: [
                                    {
                                        required: true,
                                        message: '假期类型'
                                    }
                                ]
                            })(<Select>{setOpiton2(modalVacation)}</Select>)}
                        </Form.Item>
                        <Form.Item label="修改余额：" required style={{ marginBottom: 0 }}>
                            <Row gutter={10}>
                                <Col span={8}>
                                    {getFieldDecorator('vocationRecordType', {
                                        initialValue: 'add'
                                    })(<Select>{setOpiton(vocationRecordTypeList)}</Select>)}
                                </Col>
                                <Col span={8}>
                                    <Form.Item>
                                        {getFieldDecorator('leaveBalance', {
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '请输入余额数'
                                                }
                                            ]
                                        })(<InputNumber style={{ width: '100%' }} step={0.5} min={0} />)}
                                    </Form.Item>
                                </Col>
                                <Col span={8}>
                                    {getFieldDecorator('timeUnitType', {
                                        initialValue: '1'
                                    })(<Select>{setOpiton(timeUnitTypeList)}</Select>)}
                                </Col>
                            </Row>
                        </Form.Item>
                        {form.getFieldsValue(['vocationRecordType']).vocationRecordType === 'add' ? (
                            <Form.Item label="余额有效期：">
                                {getFieldDecorator('radioTime', {
                                    initialValue: true
                                })(
                                    <Radio.Group>
                                        <Radio value>今年余额</Radio>
                                        <Radio value={false}>明年余额</Radio>
                                    </Radio.Group>
                                )}
                            </Form.Item>
                        ) : (
                            ''
                        )}
                        <Form.Item label="修改原因：" help="2-200个字符">
                            {getFieldDecorator('remark', {
                                rules: [
                                    {
                                        min: 2,
                                        max: 200,
                                        message: '请输入2~200个字符'
                                    }
                                ]
                            })(<TextArea autosize={{ minRows: 3, maxRows: 5 }} />)}
                        </Form.Item>
                        <div className={styles.notes}>
                            <i className={styles.i}>注：</i>
                            <div className={styles.fo}>
                                此处不支持调休余额修改，可在加班记录表里的“手动补录”补录加班时长
                            </div>
                        </div>
                    </Form>
                </ConfigProvider>
            </Modal>
        </PageHeaderWrapper>
    );
};

export default connect(({ loading, vacationBalance, user }) => ({
    user,
    vacationBalance,
    loading
}))(Form.create()(VacationBalance));
